package com.xunwulian.cmeb.command;

import com.xunwulian.base.constant.CmebErrorCode;
import com.xunwulian.base.entity.AppEntity;
import com.xunwulian.base.exception.ErrorCodeException;
import com.xunwulian.base.util.DigestUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Receiver {

    private AppEntity appEntity;

    private static final Logger logger = LoggerFactory.getLogger(Receiver.class);

    public Receiver(AppEntity appEntity) {
        this.appEntity = appEntity;
    }

    public JSONArray actionPost(APICode apiCode, String param) throws ErrorCodeException {

        String url = generateUrl(apiCode, param, appEntity.getCmebAppId()
                , appEntity.getCmebPasswd(), appEntity.getCmebIp(), appEntity.getCmebPort()
                , appEntity.getCmebVersion());

        String respMsg = getMsg(url);

        JSONObject jsonObject = new JSONObject(respMsg);

        JSONArray result = null;
        if ("0".equals(jsonObject.getString("status"))) {
            result = jsonObject.getJSONArray("result");
        } else {
            String status = jsonObject.getString("status");
            String message = jsonObject.getString("message");

            throw new ErrorCodeException(status, message);
        }

        return result;
    }

    public String generateUrl(APICode apiCode, String param, String cmebAppId, String cmebPasswd
            , String cmebIp, String cmebPort, String cmebVersion) {

        // 由 EC 按照规则生成，生成规则：	APPID+YYYYMMDDHHMISS + 8位数字序列（EC 自行生成）
        String transid = cmebAppId
                + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                + String.format("%08d", System.currentTimeMillis());

        // token = (appid + httpClientPwd + transid)加密 MD5(sha256)加密,返回 64 位小写十六进制字符串
        String token = DigestUtil.sha256(cmebAppId + cmebPasswd + transid);

        String paramResult = "&appid=" + cmebAppId + "&transid=" + transid + "&token=" + token;


        String PATH = "http://" + cmebIp + ":" + cmebPort + "/" + cmebVersion + "/";
        String url = PATH + apiCode.getIface() + "?" + param + "&ebid=" + apiCode.getEbid() + paramResult;
        logger.info(url);

        return url;
    }

    public String getMsg(String url) throws ErrorCodeException {

        HttpClient client = HttpClientBuilder.create().build();
        String respMsg = null;
        try {
            HttpResponse mRes = client.execute(new HttpGet(url));
            if (mRes.getEntity() != null) {
                respMsg = EntityUtils.toString(mRes.getEntity()).toLowerCase();
                logger.info("respMsg:" + respMsg);
            }
        } catch (IOException e) {
            e.printStackTrace();

            throw new ErrorCodeException(String.valueOf(CmebErrorCode.E1000.getType()),
                    CmebErrorCode.E1000.getDesc());
        }

        return respMsg;
    }

}
